<template>
  <div id="login_container" class="login overflow-hidden animate__animated">
    <div class="login_box w-[100%] mt-0 lg:mt-[-50px] md:pl-[170px] lg:w-[50%] flex justify-center">
      <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form w-[440px] md:w-[50%]">
        <div class="flex flex-col items-start">
          <img src="@/assets/logo/login_login.png" class="w-[81px]" alt="" />
          <!-- <img src="@/assets/logo/Hlmpay.png" class="h-[71px] mt-[30px]" alt="" /> -->
        </div>
        <div class="mt-[18px] font-bold text-[34px] title text-black">
         <!--    <img src="@/assets/images/form_content.png" class="max-w-[100%]" alt="" /> -->
        </div>
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" placeholder="账号"> </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off" placeholder="密码" @keyup.enter="handleLogin">
          </el-input>
        </el-form-item>
        <el-form-item v-if="captchaEnabled" prop="code">
          <div class="flex justify-between w-[100%] items-center">
            <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="验证码" style="width: 63%" @keyup.enter="handleLogin">
            </el-input>
            <img :src="codeUrl" class="w-[30%] h-[38px] rounded-[10px] cursor-pointer" @click="getCode" />
          </div>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">记住密码</el-checkbox>
        <el-form-item v-if="false" style="float: right">
          <el-button circle title="微信登录" @click="doSocialLogin('wechat')">
            <svg-icon icon-class="wechat" />
          </el-button>
          <el-button circle title="MaxKey登录" @click="doSocialLogin('maxkey')">
            <svg-icon icon-class="maxkey" />
          </el-button>
          <el-button circle title="TopIam登录" @click="doSocialLogin('topiam')">
            <svg-icon icon-class="topiam" />
          </el-button>
          <el-button circle title="Gitee登录" @click="doSocialLogin('gitee')">
            <svg-icon icon-class="gitee" />
          </el-button>
          <el-button circle title="Github登录" @click="doSocialLogin('github')">
            <svg-icon icon-class="github" />
          </el-button>
        </el-form-item>
        <el-form-item style="width: 100%; margin: 0">
          <el-button :loading="loading" type="primary" style="width: 100%; height: 50px" @click.prevent="handleLogin">
            <span v-if="!loading" class="text-white">登 录</span>
            <span v-else class="text-white">登 录 中...</span>
          </el-button>
          <div v-if="register" style="float: right">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <div class="hidden xl:block relative h-[100%] w-[50%]">
      <img
        src="@/assets/images/login_right1.png"
        class="absolute right-[40px] top-[25%] z-20 mt-[-80px] max-w-[100%] animate__animated animate__lightSpeedInLeft"
        alt=""
      />
      <img
        src="@/assets/images/login_right2.png"
        class="absolute right-0 top-[25%] z-10 mt-[80px] max-w-[100%] animate__animated animate__lightSpeedInLeft"
        alt=""
      />
    </div>

    <!--    <div class="mask"></div>-->
  </div>
</template>

<script setup lang="ts">
import { getCodeImg } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import leftImage from '@/assets/images/login_bg.png';

const userStore = useUserStore();
const router = useRouter();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: ''
} as LoginData);

const loginRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: '请输入您的租户编号' }],
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(true);

// 注册开关
const register = ref(false);
const redirect = ref(undefined);
const loginRef = ref<ElFormInstance>();

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
  },
  { immediate: true }
);

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        // 否则移除
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        document.getElementById('login_container').classList.add('animate__fadeOutTopRight');
        document.getElementById('login_container').style.setProperty('--animate-duration', '0.5s');
        setTimeout(async () => {
          router.push('/');
          loading.value = false;
        }, 500);
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  } as LoginData;
};

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  authBinding(type, loginForm.value.tenantId).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      // 获取授权地址跳转
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const loadingServe = ElLoading.service({
  lock: true,
  background: 'rgba(255, 255, 255, 0.7)'
});

onMounted(() => {
  const img = new Image();
  img.src = leftImage;
  img.onload = () => {
    loadingServe.close();
    document.querySelector('.login-form').classList.add('login-form-show');
    getCode();
    getLoginData();
  };
});
</script>

<style lang="scss" scoped>
#login_container {
  background: url('@/assets/images/login_bg.png') no-repeat;
  background-size: 100% cover;
}
.login {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-size: cover;
  width: 100%;
  height: 100vh;
}

.title {
  font-family: 'ping_fang';
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial, serif;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}

@keyframes BorderRotaBottom {
  to {
    transform: translateX(-50%) translateY(-50%) rotate(360deg);
  }

  from {
    transform: translateX(-50%) translateY(-50%) rotate(0deg);
  }
}

.login_left {
  height: 100%;
  width: 50%;
  object-position: 0vmax 0vmax;
  object-fit: cover;
  background-size: cover;
  border-radius: 0 80px 80px 0;
  transform: translateX(-50vw);
}

.login_left_move {
  transform: translateX(0);
  transition: 0.4s linear;
}

.login_box {
  .login-form {
    opacity: 0;
    width: 440px;
    .el-input {
      height: 38px;
      input {
        height: 38px;
      }
    }

    .input-icon {
      height: 39px;
      width: 14px;
      margin-left: 0px;
    }
  }
}
.login-form-show {
  opacity: 1 !important;
  transition: 2s;
}

:deep(.el-input__wrapper) {
  background-color: rgba($color: #fff, $alpha: 0.5);
}

.animate__animated.animate__bounce {
  --animate-duration: 2s;
}
</style>
